import React from 'react'
import PropTypes from 'prop-types'
import {routerRedux} from 'dva/router'
import {connect} from 'dva'
import {Button, Col, Icon, Popconfirm, Row, Upload} from 'antd'
import {Page} from 'components'
import queryString from 'query-string'
import List from './components/List'
import Filter from './components/Filter'
import {api} from 'config'
import Modal from './components/Modal'
import {ChartCard} from 'components/Charts'
import {message} from "antd/lib/index"

const Operator = ({
                    location, dispatch, operator, loading,
                  }) => {
  const {query, pathname} = location
  const {
    list, empList, figureIp, friendCircleType, source, operateStatus, departments, stat, pagination, expandForm, currentItem, modalVisible, modalType, selectedRowKeys,
  } = operator

  const handleRefresh = (newQuery) => {
    dispatch(routerRedux.push({
      pathname,
      search: queryString.stringify({
        ...query,
        ...newQuery,
      }),
    }))
  }

  const UploadProps = {
    name: 'excel',
    accept: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
    action: `${api.importEmp}`,
    headers: {
      authorization: 'authorization-text',
    },
    onChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件已经上传成功`)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`)
      }
    },
  }

  const ColProps = {
    xs: 24,
    sm: 12,
    style: {
      marginBottom: 16,
    },
  }

  const modalProps = {
    item: modalType === 'create' ? {} : currentItem,
    visible: modalVisible,
    width: 1600,
    empList,
    figureIp,
    friendCircleType,
    source,
    operateStatus,
    maskClosable: false,
    confirmLoading: loading.effects[`operator/${modalType}`],
    title: '新增微信运营号',
    wrapClassName: 'vertical-center-modal',
    handleSearch (key) {
      if (key) {
        dispatch({
          type: 'operator/searchEmp',
          payload: {
            key,
          },
        })
      }
    },
    onOk (data) {
      dispatch({
        type: `operator/${modalType}`,
        payload: data,
      })
        .then(() => {
          handleRefresh()
        })
    },
    onCancel () {
      dispatch({
        type: 'operator/hideModal',
      })
    },
  }

  const listProps = {
    rowKey: 'id',
    dataSource: list,
    loading: loading.effects['operator/query'],
    pagination,
    location,
    onChange (page) {
      handleRefresh({
        current: page.current,
        size: page.pageSize,
      })
    },
    openTab (record) {
      const tab = {
        name: '运营号-'.concat(record.wxNo ? record.wxNo : record.wxId),
        route: '/operator/'.concat(record.wxId),
      }
      dispatch({
        type: 'app/addTab',
        payload: {
          menu: tab,
        },
      })
    },
    rowSelection: {
      selectedRowKeys,
      onChange: (keys) => {
        dispatch({
          type: 'operator/updateState',
          payload: {
            selectedRowKeys: keys,
          },
        })
      },
    },
  }

  const filterProps = {
    filter: {
      ...query,
    },
    stat,
    empList,
    departments,
    figureIp,
    friendCircleType,
    source,
    operateStatus,
    searchDic (sn) {
      dispatch({
        type: 'dictionary/queryBySn',
        payload: {
          sn,
        },
      })
    },
    handleSearch (key) {
      if (key) {
        dispatch({
          type: 'operator/searchEmp',
          payload: {
            key,
          },
        })
      }
    },
    expandForm,
    toggleForm () {
      dispatch({type: 'operator/toggleForm'})
    },
    onFilterChange (value) {
      handleRefresh({
        ...value,
        current: 1,
      })
    },
  }

  const onAdd = () => {
    dispatch({
      type: 'operator/showModal',
      payload: {
        modalType: 'create',
      },
    })
  }

  const handleDeleteItems = () => {
    dispatch({
      type: 'operator/multiDelete',
      payload: {
        ids: selectedRowKeys,
      },
    })
      .then(() => {
        handleRefresh({
          current: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
        })
      })
  }

  return (
    <div>
      <Row gutter={24}>
        <ChartCard style={{marginBottom: 12}}>
          <Filter {...filterProps}/>
        </ChartCard>
      </Row>
      <Row gutter={24}>
        <Page inner>
          <Row gutter={24}>
            <Col {...ColProps} xl={{span: 24}} md={{span: 24}} sm={{span: 24}}>
              <div style={{display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', float: 'right'}}>
                <Button className="margin-right" type="primary" onClick={onAdd}>添加运营号</Button>
                {/*<a href="javascript:alert('下载模板');" target="_blank">*/}
                  {/*<Button className="margin-right"><Icon type="cloud-download-o"/>下载导入模板</Button>*/}
                {/*</a>*/}
                {/*<a href="javascript:alert('运营号导出');" target="_blank">*/}
                  {/*<Button className="margin-right"><Icon type="cloud-download-o"/>运营号导出</Button>*/}
                {/*</a>*/}
                {/*<Upload {...UploadProps}>*/}
                  {/*<Button>*/}
                    {/*<Icon type="upload"/> 导入运营号资料*/}
                  {/*</Button>*/}
                {/*</Upload>*/}
              </div>
            </Col>
          </Row>
          {
            selectedRowKeys.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              <Col>
                {`选中了 ${selectedRowKeys.length} 条数据`}
                <Popconfirm title="确定要删除这些数据吗?" placement="left" onConfirm={handleDeleteItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }
          <List {...listProps} />
          {modalVisible && <Modal {...modalProps} />}
        </Page>
      </Row>
    </div>
  )
}

Operator.propTypes = {
  operator: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({operator, loading}) => ({operator, loading}))(Operator)
